using System;
using System.IO;
using Common.Core.Serialization;
using Microsoft.Practices.ObjectBuilder2;

namespace Common.Unity.Extensions.Serialization
{
	public abstract class SerializationPolicyBase : IObjectCreationPolicy
	{
    	readonly IStreamResolver resolver;

    	protected SerializationPolicyBase( IStreamResolver resolver )
    	{
    		this.resolver = resolver;
    	}

    	public IStreamResolver Resolver
    	{
    		get { return resolver; }
    	}

    	object IObjectCreationPolicy.Create( IBuilderContext context )
		{
			var item = ResolveItem( context );
			return item;
		}

		object ResolveItem( IBuilderContext context ) 
		{
			Type type;
			if ( BuildKey.TryGetType( context.BuildKey, out type ) )
			{
				var stream = Resolver.ResolveStream();
				if ( stream != null )
				{
					var result = Deserialize( type, stream );
					return result;
				}
				throw new InvalidOperationException( string.Format( "Invalid stream resolved by '{0}'.", GetType().Name ) );
			}
			return context.Existing;
		}

		protected abstract object Deserialize( Type targetType, Stream stream );
	}
}